package com.campus.help.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.common.PageResult;
import com.campus.help.common.Result;
import com.campus.help.entity.Banner;
import com.campus.help.service.BannerService;
import com.campus.help.utils.FileStorageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 轮播图管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/banners")
public class AdminBannerController {

    @Autowired
    private BannerService bannerService;

    @Autowired
    private FileStorageUtils fileStorageUtils;

    /**
     * 分页查询轮播图列表
     * @param page 页码
     * @param size 每页大小
     * @param keyword 关键词
     * @param status 状态
     * @return 分页结果
     */
    @GetMapping
    public Result<PageResult<Banner>> getBannerPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {

        try {
            log.info("查询轮播图列表，页码：{}，每页大小：{}，关键词：{}，状态：{}", page, size, keyword, status);

            Page<Banner> pageParam = new Page<>(page, size);
            IPage<Banner> result = bannerService.getBannerPage(pageParam, keyword, status);


            PageResult<Banner> pageResult = new PageResult<Banner>(
                result.getCurrent(),
                result.getSize(),
                result.getTotal(),
                result.getRecords()
            );

            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询轮播图列表失败", e);
            return Result.error("查询失败");
        }
    }

    /**
     * 根据ID查询轮播图详情
     * @param id 轮播图ID
     * @return 轮播图详情
     */
    @GetMapping("/{id}")
    public Result<Banner> getBannerById(@PathVariable Long id) {
        try {
            log.info("查询轮播图详情，ID：{}", id);

            Banner banner = bannerService.getById(id);
            if (banner == null) {
                return Result.error("轮播图不存在");
            }

            // 生成图片访问URL
            if (banner.getImageUrl() != null && !banner.getImageUrl().isEmpty()) {
                try {
                    // 如果不是完整URL，则生成完整访问URL
                    if (!banner.getImageUrl().startsWith("http://") && !banner.getImageUrl().startsWith("https://")) {
                        String imageUrl = fileStorageUtils.getFileUrl(banner.getImageUrl());
                        banner.setImageUrl(imageUrl);
                    }
                } catch (Exception e) {
                    log.warn("获取轮播图URL失败：{}", banner.getImageUrl());
                }
            }

            return Result.success(banner);
        } catch (Exception e) {
            log.error("查询轮播图详情失败，ID：{}", id, e);
            return Result.error("查询失败");
        }
    }

    /**
     * 添加轮播图
     * @param banner 轮播图信息
     * @param imageFile 图片文件
     * @return 操作结果
     */
    @PostMapping
    public Result<String> addBanner(@ModelAttribute Banner banner,
                                   @RequestParam(value = "imageFile", required = false) MultipartFile imageFile) {
        try {
            log.info("添加轮播图，标题：{}", banner.getTitle());

            // 参数校验
            if (banner.getTitle() == null || banner.getTitle().trim().isEmpty()) {
                return Result.error("轮播图标题不能为空");
            }

            if (imageFile == null || imageFile.isEmpty()) {
                return Result.error("轮播图图片不能为空");
            }

            boolean success = bannerService.addBanner(banner, imageFile);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加轮播图失败", e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 更新轮播图
     * @param id 轮播图ID
     * @param banner 轮播图信息
     * @param imageFile 图片文件（可选）
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public Result<String> updateBanner(@PathVariable Long id,
                                      @ModelAttribute Banner banner,
                                      @RequestParam(value = "imageFile", required = false) MultipartFile imageFile) {
        try {
            log.info("更新轮播图，ID：{}，标题：{}", id, banner.getTitle());

            // 参数校验
            if (banner.getTitle() == null || banner.getTitle().trim().isEmpty()) {
                return Result.error("轮播图标题不能为空");
            }

            banner.setId(id);
            boolean success = bannerService.updateBanner(banner, imageFile);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新轮播图失败，ID：{}", id, e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除轮播图
     * @param id 轮播图ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteBanner(@PathVariable Long id) {
        try {
            log.info("删除轮播图，ID：{}", id);

            // 检查是否存在
            Banner banner = bannerService.getById(id);
            if (banner == null) {
                return Result.error("轮播图不存在");
            }

            boolean success = bannerService.deleteBanner(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除轮播图失败，ID：{}", id, e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 切换轮播图状态
     * @param id 轮播图ID
     * @param requestBody 请求体，包含status字段
     * @return 操作结果
     */
    @PutMapping("/{id}/status")
    public Result<String> toggleStatus(@PathVariable Long id, @RequestBody Map<String, Integer> requestBody) {
        try {
            Integer status = requestBody.get("status");
            log.info("切换轮播图状态，ID：{}，状态：{}", id, status);

            // 检查是否存在
            Banner banner = bannerService.getById(id);
            if (banner == null) {
                return Result.error("轮播图不存在");
            }

            // 状态校验
            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态值无效");
            }

            boolean success = bannerService.toggleStatus(id, status);
            if (success) {
                String statusText = status == 1 ? "启用" : "禁用";
                return Result.success(statusText + "成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("切换轮播图状态失败，ID：{}", id, e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 上传图片
     * @param file 图片文件
     * @return 上传结果
     */
    @PostMapping("/upload")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            log.info("上传轮播图图片，文件名：{}", file.getOriginalFilename());

            // 文件类型校验
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }

            // 上传文件
            String fileName = fileStorageUtils.uploadFile(file, "banners");
            String imageUrl = fileStorageUtils.getFileUrl(fileName);

            Map<String, String> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("imageUrl", imageUrl);

            return Result.success(result);
        } catch (Exception e) {
            log.error("上传轮播图图片失败", e);
            return Result.error("上传失败：" + e.getMessage());
        }
    }
}
